<template>
  <view style="text-align: center" class="page-main">
    <view class="rightClass" v-if="canvasStatus">
      <canvas id="canvasOne" :style="{'width':clientWidthCanvas+'px','height':clientHeightCanvas+'px'}" canvas-id="canvasOne"></canvas>
      <canvas canvas-id="qrcode" :style="{width: `${qrcodeSize}px`, height: `${qrcodeSize}px`}" style="position: absolute;top: -100px;z-index: -9"/>
    </view>
    <image class="rightClass" :src="poster"></image>
  </view>
</template>

<script>
import store from "@/store";
// #ifdef H5 || APP-PLUS
import uQRCode from '@/js_sdk/Sansnn-uQRCode/uqrcode.js'
import share from "@/utils/share";
// #endif
export default {
  data() {
    return {
      usersInfoObj: {},
      base64List: ['/pagesWater/static/invitationBg.png'],
      PromotionCode: '',
      qrcodeSize: 100,
      poster: '',
      canvasStatus: true, //海报绘图标签
      spreadList: [],
      clientWidthCanvas: '',
      clientHeightCanvas: '',
    }
  },
  async onLoad() {
   // #ifdef H5
    share.getShareConfig({}, this.$WXMENU);
   // #endif
    uni.getSystemInfo({
      success: (res) => {
        this.clientWidthCanvas = uni.upx2px(500)
        this.clientHeightCanvas = uni.upx2px(900)
      }
    })
    await this.getInfo()
    await this.make()
  },
  methods: {
    async getInfo() {
      await store.dispatch('USERINFO').then(res => {
        this.usersInfoObj = res
      }).catch(err => {
        if (err.code == 401) {
          uni.navigateTo({
            url:'/pagesWater/users/login'
          })
        }
      })
    },
    // 生成二维码；
    make() {
      let that = this;
      const strMap = {
      	"H5-dev": "https://dev-manage.julimeng.com/2h5/#/",
      	"H5-test": "https://test-manage.julimeng.com/2h5/#/",
      	"H5-uat": "https://dev-manage.julimeng.com/2h5/#/",
      	"H5-prod": "https://manage.shengdaiqifu.com/2h5/#/",
      };
      // #ifdef APP-PLUS
      let href = 'https://manage.shengdaiqifu.com/2h5/#/'
      // #endif
      // #ifdef H5
      let href = strMap[process.env.ENV_TYPE]               
      // #endif
	  
      uni.showLoading({
        title:'生成海报中...'
      })
      uQRCode.make({
        canvasId: 'qrcode',
        text: `${href}pages/waterReport/index?spreadUid=${that.usersInfoObj.id}&channelCode=fenxianggongju`,
        size: this.qrcodeSize,
        margin: 2,
        success: res => {
          that.PromotionCode = res;
          setTimeout(() => {
            that.PosterCanvas(this.base64List[0], that.PromotionCode, that.usersInfoObj.nickname,0);
          }, 300);
        },
        complete: (res) => {
        },
        fail: res => {
          uni.hideLoading();
          that.$util.Tips({
            title: '海报二维码生成失败！'
          });
        }
      })
    },
	
	
	PosterCanvas: function(arrImages, code, nickname, index) {
		let popWidth = '',
			popHeight = ''
		uni.createSelectorQuery()
			.in(this)
			.select('.page-main')
			.boundingClientRect(data => {
				popWidth = uni.upx2px(data.width)
				popHeight = uni.upx2px(data.height)
			})
			.exec();
	
		let context = uni.createCanvasContext('canvasOne')
		context.clearRect(0, 0, 0, 0);
		let hW = uni.upx2px(600);
		// let hH = uni.upx2px(280);
		let that = this;
		uni.getImageInfo({
			src: arrImages,
			success: function(res) {
				context.drawImage(arrImages, 0, 0, that.clientWidthCanvas, that
					.clientHeightCanvas);
				context.save();
				// context.drawImage(code, uni.upx2px(187), (((that.clientHeightCanvas - hW) / 2) +
				// 	uni.upx2px(204)), uni.upx2px(152), uni.upx2px(158))
	
				context.drawImage(
					code,
					that.clientWidthCanvas / 5,
					that.clientHeightCanvas / 1.85,
					that.clientWidthCanvas / 1.64,
					that.clientHeightCanvas / 3.6,
				);
				// context.drawImage(code, popWidth/2, popHeight/2, 76, 76);
				context.restore();
				context.setFontSize(28);
				// context.fillText(nickname, 270, 980);
				// context.fillText('邀请您加入', 270, 1020);
				setTimeout(() => {
					context.draw(true, function() {
						uni.canvasToTempFilePath({
							destWidth: 750,
							destHeight: 1190,
							canvasId: 'canvasOne',
							fileType: 'jpg',
							success: function(res) {
								// 在H5平台下，tempFilePath 为 base64
								uni.hideLoading();
	
								// that.spreadList[index].pic = res.tempFilePath;
								that.$set(that, 'poster', res
									.tempFilePath);
	
								that.$set(that, 'canvasStatus', false);
							}
						})
					})
				}, 100);
			},
			fail: function(err) {
				uni.hideLoading();
				that.$util.Tips({
					title: '无法获取图片信息'
				});
			}
		});
	},
	
    // 点击保存海报
    bindchange(e) {
      // const canvas = document.getElementById('canvasOne');
      // canvas.toBlob(function(blob) {
      //   navigator.msSaveBlob(blob, 'canvas-image.png');
      // }, 'image/png');
      const canvasDataUrl = this.poster
      // 创建一个a标签
      const a = document.createElement('a');
      a.href = canvasDataUrl;
      a.download = 'canvas-image.png';  // 可以自定义文件名和格式
      // 将a标签添加到页面中，并模拟点击下载
      document.body.appendChild(a);
      a.click();
      // 下载完成后移除a标签
      document.body.removeChild(a);
      //调用预览图片的方法
      // uni.previewImage({
      //   urls: this.base64List,
      //   current: 0, //点击图片传过来的下标
      //   success: (res) => {
      //     console.log('预览图片成功',res,this.poster);
      //     // uni.showToast({
      //     // 	title: '预览图片成功'
      //     // })
      //   }
      // })

    },
    shareLink() {
      uni.setClipboardData({
        data: location.origin+location.pathname + `#/?spreadUid=${this.usersInfoObj.id}`,
        showToast: true,
        success: function() {
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.rightClass {
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
}
.textStyle {
  position: fixed;
  z-index: 9;
  text-align: center;
  color: #FFFFFF;
  width: 340rpx;
  left: 50%;
  transform: translateX(-50%);
  bottom: 40rpx;
}
</style>